﻿#define _CRT_SECURE_NO_WARNINGS
#include"List.h"


//申请一个节点
LTNode* BuyNode(LTDatatype x)
{
	//双链表，双向带头循环链表
	LTNode* node = (LTNode*)malloc(sizeof(LTNode));
	node->data = x;
	node->next = node->prev = node;

}

//初始化
LTNode* LTInit()
{
	LTNode* Newnode = BuyNode(-1);
	return Newnode;
}

//初始化2
//LTNode* LTInit(LTNode** phead)
//{
//	assert(phead);
//	(*phead) = (LTNode*)malloc(sizeof(LTNode));
//	(*phead)->data = -1;
//	(*phead)->next = (*phead)->prev = *phead;
//}

void LTPushBack(LTNode* phead, LTDatatype x)
{
	assert(phead);
	LTNode* newnode = BuyNode(x);
	newnode->prev = phead->prev;
	newnode->next = phead;
	phead->prev->next = newnode;
	phead->prev = newnode;

}
void LTPushFront(LTNode* phead, LTDatatype x)
{
	assert(phead);
	LTNode* newnode = BuyNode(x);

	newnode->next = phead->next;
	newnode->prev = phead;
	phead->next->prev = newnode;
	phead->next = newnode;
}

void LTPrint(LTNode* phead)
{
	assert(phead);
	LTNode* pcur = phead->next;
	while (pcur != phead)
	{
		printf("%d -> ", pcur->data);
		pcur = pcur->next;
	}
	printf("\n");
}
bool LTEmpty(LTNode* phead)
{
	assert(phead);
	return phead->next == phead;
}



//尾删
void LTPopBack(LTNode* phead)
{
	assert(phead);
	LTNode* ret = phead->prev;
	ret->prev->next = phead;
	phead->prev = ret->prev;
	free(ret);
	ret = NULL;
}
void LTPopFront(LTNode* phead)
{
	assert(phead);
	LTNode* ret = phead->next;
	phead->next = ret->next;
	ret->next->prev = phead;
	free(ret);
	ret = NULL;
}



//在pos位置之后插⼊数据
void LTInsert(LTNode* pos, LTDatatype x)
{
	assert(pos);
	LTNode* newnode = BuyNode(x);

	newnode->next = pos->next;
	newnode->prev = pos;

	pos->next->prev = newnode;
	pos->next = newnode;

}

void LTErase(LTNode* pos)
{
	assert(pos);

	pos->next->prev = pos->prev;
	pos->prev->next = pos->next;
}

LTNode* LTFind(LTNode* phead, LTDatatype x)
{
	assert(phead);
	LTNode* pcur = phead->next;
	while (pcur != phead)
	{
		if (pcur->data == x)
		{
			return pcur;
		}
		pcur = pcur->next;
	}
	return NULL;
}

//消除链表
void LTDesTroy(LTNode* phead)
{
	LTNode* pcur = phead->next;
	while (pcur != phead)
	{
		LTNode* new = pcur->next;
		free(pcur);
		pcur = new;
	}
	free(phead);
	phead=NULL;
}